package com.ibest.base.listener;


import com.alibaba.fastjson.JSONObject;
import com.ibest.base.entity.CanalBinlogBean;
import com.ibest.base.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
@ConditionalOnProperty(name = "ibest.server-type",havingValue = "RocketMQ")
@RocketMQMessageListener(topic = "${ibest.canal.customer-topic}",consumerGroup = "${ibest.canal.customer-group}",selectorExpression="*")
public class CanalToTargetCustomerListener implements RocketMQListener<MessageExt> {
    @Resource
    private RedisService redisService;

    @Override
    public void onMessage(MessageExt msg) {
        String strLog = new String(msg.getBody());
        log.info("消费端服务监听到MQ消息：{}",strLog);

        CanalBinlogBean binlogBean = JSONObject.parseObject(strLog, CanalBinlogBean.class);
        String type = binlogBean.getType();
        //如果不是ddl语句
        if(!binlogBean.isDdl()){
            String directory = binlogBean.getTable();
            List<JSONObject> list = binlogBean.getData();
            //新增或更新直接set,删除则删除key
            if("INSERT".equals(type) || "UPDATE".equals(type)){
                redisService.sendMsgTopic(binlogBean);
//                redisService.setCanalBinlogBean(binlogBean);
//                    redisUtil.set(key,JSONObject.toJSONString(data),expireTime);

            }else if ("DELETE".equals(type)) {
                redisService.sendMsgTopic(binlogBean);
//                redisService.delCanalBinlogBean(binlogBean);
//                    redisUtil.delete(key);
            }
        }
    }
}